package http;

import android.content.Context;
import android.text.TextUtils;

import com.google.gson.Gson;
import com.loopj.android.http.RequestParams;

import org.apache.http.Header;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashSet;
import java.util.Set;

import log.LogManager;
import utils.RequestEncryDecryptUtil;
import utils.SharedPreUtil;
import utils.common.StringUtils;

/**
 * Created by hqw on 2015/9/8.
 */
public class AysncHttpRequest {
    private Gson mGson;

    private static AysncHttpRequest _aysncHttpRequest;

    public AysncHttpRequest() {
        mGson = new Gson();
    }

    public static AysncHttpRequest getInstance() {
        if (_aysncHttpRequest == null) {
            _aysncHttpRequest = new AysncHttpRequest();
        }
        return _aysncHttpRequest;
    }

    /**
     * 请求对列，重复点击请求处理，判断当前请求是否已经发送，如果发送还没有响应则不发送
     */
    public static Set<String> requestQueue = new HashSet<String>();


    /**
     * post 方式 请求  返回指定类型
     *
     * @param mContext
     * @param url        路径
     * @param requestMap 参数值，转json 传输
     * @param callback   结果回调
     */
    public void post(final Context mContext, String url, RequestMapBean requestMap, final ResultCallback callback) {
        String userId = SharedPreUtil.getInstance(mContext).getValue(SharedPreUtil.USER_ID);
        requestMap.put("userId", userId);
        RequestParams param = RequestEncryDecryptUtil.commonJsonRequestParams(mContext, requestMap);
        post_l(mContext, url, param, callback);
    }

    /**
     * get 方式 请求  返回指定类型
     *
     * @param mContext
     * @param url        路径
     * @param requestMap 参数值，转json 传输
     * @param callback   结果回调
     */
    public void get(final Context mContext, String url, RequestMapBean requestMap, final ResultCallback callback) {
        String userId = SharedPreUtil.getInstance(mContext).getValue(SharedPreUtil.USER_ID);
        requestMap.put("userId", userId);
        RequestParams param = RequestEncryDecryptUtil.commonJsonRequestParams(mContext, requestMap);
        get_l(mContext, url, param, callback);
    }


    /**
     * post 方式 请求  返回指定类型
     *
     * @param mContext
     * @param url        路径
     * @param requestMap 参数值，转竖线（|） 传输
     * @param callback   结果回调
     */
    public void post_common(final Context mContext, String url, RequestMapBean requestMap, final ResultCallback callback) {
        String userId = SharedPreUtil.getInstance(mContext).getValue(SharedPreUtil.USER_ID);
        requestMap.put("userId", userId);
        RequestParams param = RequestEncryDecryptUtil.commonRequestParams(mContext, requestMap);
        post_l(mContext, url, param, callback);
    }

    /**
     * get 方式 请求  返回指定类型
     *
     * @param mContext
     * @param url        路径
     * @param requestMap 参数值，转竖线（|） 传输
     * @param callback   结果回调
     */
    public void get_common(final Context mContext, String url, RequestMapBean requestMap, final ResultCallback callback) {
        String userId = SharedPreUtil.getInstance(mContext).getValue(SharedPreUtil.USER_ID);
        requestMap.put("userId", userId);
        RequestParams param = RequestEncryDecryptUtil.commonRequestParams(mContext, requestMap);
        get_l(mContext, url, param, callback);
    }

    /**
     * post 方式 请求  返回指定类型
     *
     * @param mContext
     * @param url      路径
     * @param param    参数
     * @param callback 结果回调
     */
    private void post_l(final Context mContext, String url, RequestParams param, final ResultCallback callback) {
        LogManager.getLogger().s("HTTP=>" + new Gson().toJson(requestQueue));
       /* if (!requestQueue.contains(url)) {
            requestQueue.add(url);*/
        AsyncHttpUtil.post(mContext, url, param, new BaseJsonHttpResponseParse(mContext, url) {
            @Override
            public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                super.onSuccess(statusCode, headers, response);
                try {
                    if (response != null) {
                        LogManager.getLogger().l("HTTP 请求返回值 data=======>" + response.toString());
                        int code = response.getInt("code");
                        if (code != 200) {
                            if (code != 125 || code != 107) {
                                callback.onError(response);
                            }else {
                                callback.onError(null);
                            }
                        } else {
                            String data = response.optString("data");
                            if (data != null && !StringUtils.isEmpty(data)) {
                                final String string = RequestEncryDecryptUtil.decryptBackData(mContext, data);
                                LogManager.getLogger().l("HTTP 请求返回值========>" + string);
                                if (string != null && !string.equals("{}")) {
                                    if (callback.mType == String.class) {
                                        callback.onSuccess(response, string);
                                    } else if (callback.mType == JSONObject.class) {
                                        callback.onSuccess(response, new JSONObject(string));
                                    } else {
                                        Object o = mGson.fromJson(string, callback.mType);
                                        callback.onSuccess(response, o);
                                    }
                                } else {
                                    callback.onSuccess(response, null);
                                }
                            } else {
                                callback.onSuccess(response, null);
                            }
                        }
                    } else {
                        LogManager.getLogger().l("HTTP 请求返回值 data为 null");
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    callback.onSuccess(response, null);
                }
            }

            @Override
            public void backFailure() {
                super.backFailure();
                callback.onFailure();
                LogManager.getLogger().l("HTTP 请求 failure 错误");
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) {
                super.onFailure(statusCode, headers, throwable, errorResponse);
                LogManager.getLogger().l("HTTP 请求 failure 错误 statusCode = " + statusCode);
                if (null == errorResponse) {
                    LogManager.getLogger().l("HTTP 请求 failure 错误 statusCode = " + statusCode);
                    JSONObject jsonObject = new JSONObject();
                    try {
                        jsonObject.putOpt("msg", "网络超时,请重试");
                        callback.onError(jsonObject);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                } else {
                    callback.onError(errorResponse);
                }
            }

            @Override
            public void onCancel() {
                super.onCancel();
                callback.onCancel();
            }
        });
        //}
    }

    /**
     * get 方式 请求  返回指定类型
     *
     * @param mContext
     * @param url      路径
     * @param param    参数值
     * @param callback 结果回调
     */
    private void get_l(final Context mContext, String url, RequestParams param, final ResultCallback callback) {
       /* if (!requestQueue.contains(url)) {
            requestQueue.add(url);*/
        AsyncHttpUtil.get(mContext, url, param, new BaseJsonHttpResponseParse(mContext, url) {
            @Override
            public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                super.onSuccess(statusCode, headers, response);
                if (response != null) {
                    LogManager.getLogger().l("HTTP 请求返回值 data=======>" + response.toString());
                    int code = 0;
                    try {
                        code = response.getInt("code");
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    try {
                        if (code != 200) {
                            if (code != 125 || code != 107) {
                                callback.onError(response);
                            }else {
                                callback.onError(null);
                            }
                        } else {
                            String data = response.optString("data");
                            if (data != null && !TextUtils.isEmpty(data)) {
                                final String string = RequestEncryDecryptUtil.decryptBackData(mContext, data);
                                if (string != null && !string.equals("{}")) {
                                    LogManager.getLogger().l("HTTP 请求返回值=======>" + string);
                                    if (callback.mType == String.class) {
                                        callback.onSuccess(response, string);
                                    } else if (callback.mType == JSONObject.class) {
                                        callback.onSuccess(response, new JSONObject(string));
                                    } else {
                                        Object o = mGson.fromJson(string, callback.mType);
                                        callback.onSuccess(response, o);
                                    }
                                } else {
                                    callback.onSuccess(response, null);
                                }
                            } else {
                                callback.onSuccess(response, null);
                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                } else {
                    LogManager.getLogger().l("HTTP 请求返回值 data为 null");
                }
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) {
                super.onFailure(statusCode, headers, throwable, errorResponse);
                LogManager.getLogger().l("HTTP 请求 failure 错误 statusCode = " + statusCode);
                if (null == errorResponse) {
                    LogManager.getLogger().l("HTTP 请求 failure 错误 statusCode = " + statusCode);
                    JSONObject jsonObject = new JSONObject();
                    try {
                        jsonObject.putOpt("msg", "网络超时,请重试");
                        callback.onError(jsonObject);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                } else {
                    callback.onError(errorResponse);
                }
            }

            @Override
            public void backFailure() {
                super.backFailure();
                callback.onFailure();
                LogManager.getLogger().l("HTTP 请求 failure 错误");
            }
        });
    }
    //}

}
